var express = require('express');
var fs = require('fs');
var path = require('path')
var multer = require('multer');  // 主要用于 form-data数据传输， 用于文件上传
var userModel = require('../model/user')
var roleModel = require('../model/roles')
var wxUserModel = require('../model/wxuser')
var menuModel = require('../model/menu')
var router = express.Router();
var getMd5 = require('../utils/md5')
var jwt = require('jsonwebtoken');
var axios = require('axios');
// 传到哪里
// 文件名字
const storage = multer.diskStorage({
  // 位置：
  destination:(req,file,cb)=>{
      var dir = path.join(__dirname,'../upload'); 
       try {
           // 检查文件是否存在
           fs.accessSync(dir);
       } catch(err){
           // 创建文件夹
           fs.mkdirSync(dir)
       }
      // 图片地址文件地址
      return cb(null,dir)
  },
  // 图片名字
  filename:(req,file,cb)=>{
      
    cb(null, Date.now() + path.extname(file.originalname))
  }
})

// 文件过滤器
const fileFilter = (req, file, cb) => {
  // 允许的文件类型
  const imgTypes = /jpeg|jpg|png/;
  const extname = imgTypes.test(path.extname(file.originalname).toLowerCase());
  const mimetype = imgTypes.test(file.mimetype);

  if (mimetype && extname) {
    return cb(null, true);
  } else {
    cb(new Error('Only jpg, jpeg, and png files are allowed.'));
  }
};

// const upload = multer({
//   storage:storage,
//   fileFilter: fileFilter,
//   limits:{
//     fileSize: 1024 * 2,   // 2k
//   }
// });

const upload = multer({
  storage:storage
});
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

// 微信登录
router.post('/wx/login',async (req,res)=>{
  const {code,nickName,avatarUrl} = req.body;
  let resData = await axios({
    method:'get',
    url:'https://api.weixin.qq.com/sns/jscode2session',
    params:{
      appid:'wxeb9a65b7592e79d8',
      secret:'e2b5ef3e97d18c06624403a54b07d2bf',
      js_code:code,
      grant_type:'authorization_code'
    }
  })
  const { session_key, openid } = resData.data; 
  // 查询数据库里是否有 openid
  let [userInfo] =await wxUserModel.find({openid});

  if(!userInfo) {
    // 登录， 插入到数据库
    userInfo =  await wxUserModel.create({
      openid:openid,
      nickName,
      avatarUrl
    })
  }
  const token = jwt.sign({
    openid:openid,
    session_key,
    _id:userInfo._id
  },"suibian",{expiresIn:'4h'})

  res.json({
    msg:'登录成功',
    data:{
      userInfo:userInfo,
      token:'Bearer '+token
    }
  })

})
// /users+子路由路径
// 注册   /users/reg
// upload.none() ： 不接受图片
// 登录
router.post('/login',async (req,res)=>{
  console.log(req.body);
  // 默认超级管理员
  const {phone,pwd} = req.body;
  const md5Pwd = getMd5(pwd);
  // 插入数据库
  const resData = await userModel.findOne({phone:phone,pwd:md5Pwd}).populate('roleType');
  console.log(resData,'登录后的数据');
 
     if(!resData) {
        res.send({
          code:0,
          msg:'手机号或者密码错误'
        })
      return;
     }
let roleIds = resData.roleType.menus;
     let menuList =   await menuModel.find(); // 获取所有的menu
     // 思路： 根据所有的菜单 和 授权勾选的id 过滤出相应角色的菜单
   function filterMenu(menus){
     return menus.filter((option)=>{
     
      if(roleIds.includes(option._id) && option.show == 1){
          return roleIds.includes(option._id) && option.show == 1
      } else if(option.children && option.children.length>0){
         option.children =  filterMenu(option.children);
         if(option.children.length>0){
            return true;
         }
      }
    
      })
   } 

  let allMenuList =  filterMenu(menuList)

    // 生成身份凭证
    // 第一个参数:用户信息
    // 第二个参数:screct密钥
    // 设置过期时间,以s作为单位   s , m, h, d
    const token = jwt.sign({phone},"suibian",{expiresIn:'8h'})

    res.send({
      msg:'登录成功',
      code:1,
      menulist:allMenuList,
      data:resData,
      token

    })
   

   
})
// 注册
router.post('/reg',upload.single('icon'),async (req,res)=>{
  //  console.log(req.body);
  // 如何获取上传的图片
  //  console.log(req.file.filename,'图片名字');
  //  console.log(req.file,'图片名字');
   const {phone,pwd,roleId} = req.body;

   const paramObj = {phone,pwd,roleId};
   // 手机号如果重复， 提示不让重复注册
   const isHave = await userModel.findOne({phone});
   if(isHave){
      res.send({
        code:1,
        msg:'手机号已经注册'
      })
      return;
   }
   
   if(req.file){
    paramObj.icon = req.file.filename;
   }

   const md5Pwd = getMd5(pwd); //加密后的密码
   paramObj.pwd = md5Pwd;
   const resData = await userModel.create(paramObj);

  if(resData){
      // 操作 插入数据到数据库
    res.send({
      msg:'注册成功',
      code:1
    })
  } else {
    res.send({
      msg:'注册失败',
      code:0
    })
  }
 
})

// 修改密码
router.post('/update/pwd',async (req,res)=>{
   const {pwd} = req.body;

   const token =  req.get('authorization').slice(7).trim();
   const user = jwt.verify(token,'suibian');
   
   const md5Pwd = getMd5(pwd); //123456 加密后的密码
   const resData = await userModel.updateOne({phone:user.phone},{pwd:md5Pwd});
   if(resData.modifiedCount){
      res.send({
        msg:'密码更新成功',
        code:1
      })
   } else {
      res.send({
        msg:'密码更新失败',
        code:0
      })
   }

})
// 新增 注册
router.post('/add',async (req,res)=>{
  //  console.log(req.body);
   // 如何获取上传的图片
  //  console.log(req.file.filename,'图片名字');
  //  console.log(req.file,'图片名字');
  const {phone,pwd='123456',gender,nickname,birthday,status,industry,sign,icon,roleId} = req.body;
    const md5Pwd = getMd5(pwd); //加密后的密码
   const paramObj = {phone,pwd:md5Pwd,gender,nickname,birthday,status,industry,sign,icon,roleId};
   // 手机号如果重复， 提示不让重复注册
   const isHave = await userModel.findOne({phone});
   if(isHave){
      res.send({
        msg:'手机号已经注册',
        code:1
      })
      return;
   }
   
   const resData = await userModel.create(paramObj);

  if(resData){
      // 操作 插入数据到数据库
    res.send({
      msg:'新增用户成功',
      code:1
    })
  } else {
    res.send({
      msg:'新增用户失败',
      code:0
    })
  }
})

// 上传图像
router.post('/upload/img',upload.single('icon'),async (req,res)=>{
  // console.log(req.file.filename,'图片名字');  单张图片上传
  if(req.file.filename) {
      res.send({
        msg:'图片上传成功',
        data:req.file.filename,
        code:1
      })
  } else {
    res.send({
      msg:'图片上传失败',
      code:0
    })
  }
})
// 用户信息更新， 传json数据就行
router.post('/update/info', async (req,res)=>{
  // 通过id去查找要修改的数据  
 const {gender,nickname,birthday,status,industry,sign,icon,id,roleId} = req.body;

    const token =  req.get('authorization').slice(7).trim();
    const user = jwt.verify(token,'suibian');
    let resA = await userModel.findOne({phone:user.phone})

 let resData = await userModel.updateOne({_id:id || resA._id},{gender,nickname,birthday,status,industry,sign,icon,roleId} );
 let datas = await userModel.findOne({_id:id || resA._id})

 if(resData) {
    res.send({
      msg:'修改成功',
      data:datas,
      code:1
    })
 } else {
  res.send({
    msg:'修改失败',
    code:0
  })
 }
})
// 修改用户信息 
// upload.single('icon') 一张图片, name:icon
// upload.array('icon',5)  某一个 name字段的多张图片上传
router.post('/update', upload.array('icon',3), async (req,res)=>{
    // 通过id去查找要修改的数据  
    // console.log(req.file.filename,'图片名字');  单张图片上传
    console.log(req.files,'多张图片');
    let allImg = [];

    req.files.forEach((item)=>{
      allImg.push(item.filename)
    })
   const {gender,nickname,birthday,status,industry,sign,roleId} = req.body;
   const token =  req.get('authorization').slice(7).trim();
   const user = jwt.verify(token,'suibian');
 
   const  dataObj = {gender,nickname,birthday,status,industry,sign,roleId};
   if(allImg.length>0) {
     dataObj.icon = allImg;
   }
   let resData = await userModel.updateOne({phone:user.phone},dataObj );

   let datas = await userModel.findOne({phone:user.phone})
    console.log(resData);
 
   if(resData) {
      res.send({
        msg:'修改成功',
        data:datas,
        code:1
      })
   } else {
    res.send({
      msg:'修改失败',
      code:0
    })
   }
})

// 删除
router.delete('/delete',async (req,res)=>{
    //根据id去删除某一条数据
    const id = req.query.id;
    console.log(id,'删除ID'); 
  let resData = await userModel.deleteOne({_id:id});
  if(resData) {
      res.send({
        msg:'删除成功',
        code:1
      })
  } else {
    res.send({
      msg:'删除失败',
      code:0
    })
  }
})


// 删除所有
router.delete('/delete/all',async (req,res)=>{
    let resData = await userModel.deleteMany();  
    if(resData) {
        res.send({
          msg:'删除成功',
          code:1
        })
    } else {
      res.send({
        msg:'删除失败',
        code:0
      })
    }
})

// 删除多条数据
router.post('/delete/more', (req,res)=>{
  // 获取到id
  const ids = req.body.ids;  // ['1','2']
  const totalLen = ids.length;
  let curCount=0; 
  ids.forEach(async (id)=>{
      const resData = await userModel.deleteOne({_id:id});
      if(resData){
          curCount++;
      }
      if(curCount==totalLen){
          // 已经全部删除完毕
          res.send({
              data:'ok',
              code:1,
              msg:'删除成功'
          })
      } 
  })
})


// 用户详情
router.get('/detail',async (req,res)=>{
  const {id} = req.query;

  const token =  req.get('authorization').slice(7).trim();
  const user = jwt.verify(token,'suibian');
  let resA = await userModel.findOne({phone:user.phone})

  let  detailData = await userModel.findOne({_id:id || resA._id}).populate("roleType");

  res.send({
    msg:'查询成功',
    code:1,
    data:detailData
  })
  
})

// 获取所有用户列表
router.get('/list',async (req,res)=>{
 const {pageIndex, pageSize,phone, nickname, gender} =  req.query;
 const regex = new RegExp(nickname, 'i'); // 'i' 标志表示不区分大小写
   // 构建查询条件
   const query = {};
   if (phone) {
     query.phone = phone;
   }
   if (nickname) {
     query.nickname = { $regex: regex };
   }
   if (gender) {
     query.gender = gender;
   }

 let resData = {}
 let count = await userModel.countDocuments();
 let totalPage = 1;
 if(pageIndex && pageSize) {
    resData = await userModel.find(query).skip((pageIndex-1)*pageSize).limit(pageSize);
    totalPage = Math.ceil(count / pageSize);
 } else {
   resData = await userModel.find(query);
 }

 if(resData.length>=0) {
    res.send({
        msg:'查询成功',
        code:1,
        totalPage:totalPage,
        count,
        data:resData
    })
  } else {
    res.send({
        msg:'查询失败',
        code:0,
        data:resData
    })
  }

})

// 条件查询 { $regex: regex } 
router.get('/search',async (req,res)=>{
  const { phone, nickname, gender } = req.query;
  const regex = new RegExp(nickname, 'i'); // 'i' 标志表示不区分大小写

  // 构建查询条件
  const query = {};
  if (phone) {
    query.phone = phone;
  }
  if (nickname) {
    query.nickname = { $regex: regex };
  }
  if (gender) {
    query.gender = gender;
  }
  
  try {
    let resData = await userModel.find(query);
    res.send({
      msg: '查询成功',
      code: 1,
      data: resData
    });
  } catch (error) {
    res.send({
      msg: '查询失败',
      code: 0
    });
  }
})

module.exports = router;
